package com.ravi.controller;

import com.ravi.agent.PhysicalAlgorithm;
import com.ravi.common.constant.CheckExceptionEnum;
import com.ravi.common.exception.CheckException;
import com.ravi.common.utils.jwt.JWTUtils;
import com.ravi.mapper.RoomInfoMapper;
import com.ravi.model.query.AddQueueReq;
import com.ravi.model.query.AdminLoginQuery;
import com.ravi.model.query.AdminPassQuery;
import com.ravi.model.resp.R;
import com.ravi.model.vo.AdminUserVo;
import com.ravi.queue.StringQueueUtil;
import com.ravi.room.StringRoomUtil;
import com.ravi.service.intf.SendMsgService;
import com.ravi.service.intf.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
public class UserController {
	@Autowired
	private UserService userService;

	@Autowired
	private SendMsgService sendMsgService;

	@Autowired
	private StringQueueUtil stringQueueUtil;

	@Autowired
	private StringRoomUtil stringRoomUtil;

	@Autowired
	private RoomInfoMapper roomInfoMapper;

	@Autowired
	private PhysicalAlgorithm algorithm;

	@PostMapping("/admin/login")
	public R adminLogin(@RequestBody AdminLoginQuery query) {
		AdminUserVo adminUserVo = userService.adminUserLogin(query.getUsername(), query.getPassword());
		Map<String,String> paras = new HashMap<>();
		paras.put("username", adminUserVo.getUsername());
		String token = JWTUtils.getAccessToken(paras);
		return R.ok().put("user", adminUserVo).put("token", token);
	}

	@PostMapping("/admin/changepwd")
	public R changePassword(@RequestBody AdminPassQuery query, HttpServletRequest request) {
		final String username = JWTUtils.getUsername(request.getHeader("token"));
		try {
			boolean changePassword = userService.isChangePassword(username, query);
			if (changePassword) return R.ok("更改密码成功!");
			else return R.error(CheckExceptionEnum.CHANGE_PASSWORD_FAILED);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return R.error(e.getMessage());
		}
	}

	@PostMapping("/admin/sign/{checkupCode}")
	public R firstSign(@PathVariable String checkupCode) {
		String roomCode = algorithm.manage(checkupCode);
		if (StringUtils.isEmpty(roomCode)) {
			throw new CheckException(CheckExceptionEnum.PATIENT_ASSIGN_FAILED);
		}
		String areaCode = roomInfoMapper.getAreaCodeByRoomCode(roomCode);
		sendMsgService.sendMsgToRoomScreen(roomCode);
		sendMsgService.sendMsgToAreaScreen(areaCode);
		sendMsgService.sendMsgToAdminEnd();
		return R.ok("入队成功!");
	}
}
